<?php

namespace app\admin\controller;

use app\admin\model\Template as TemplateModel;
use app\admin\model\System as SystemModel;
use app\BaseController;
use think\facade\Queue;
use think\facade\Cache;

class Template extends BaseController
{
    /* 获取 */
    public function get()
    {
        if (!$this->request->auth) return show(config('status.auth'), 'Authorization Failed');
        $cid = input('cid', 0, 'intval');
        $data = TemplateModel::where('cid', $cid)->find();
        if ($data) {
            return show(config('status.success'), '查询成功', $data);
        } else {
            return show(config('status.error_find'), '查询失败');
        }
    }

    /* 修改 */
    public function modify()
    {
        if (!$this->request->auth) return show(config('status.auth'), 'Authorization Failed');
        $cid = input('cid', 0, 'intval');
        $first = input('first', '');
        $keyword1 = input('keyword1', '');
        $keyword2 = input('keyword2', '');
        $remark = input('remark', '');
        $url = input('url', '');

        $one = TemplateModel::where('cid', $cid)->find();
        if (!$one) {
            $result = TemplateModel::create([
                'cid' => $cid,
                'first' => $first,
                'keyword1' => $keyword1,
                'keyword2' => $keyword2,
                'remark' => $remark,
                'url' => $url
            ]);
        } else {
            $result = TemplateModel::update([
                'first' => $first,
                'keyword1' => $keyword1,
                'keyword2' => $keyword2,
                'remark' => $remark,
                'url' => $url
            ], ['cid' => $cid]);
        }

        if ($result) {
            return show(config('status.success'), '修改成功');
        } else {
            return show(config('status.error_update'), '修改失败');
        }
    }

    /* 获取token */
    private function getToken()
    {
        $token = Cache::get(config('cache.redis.prefix') . '_accesstoken');
        if ($token) return $token;

        $cid = input('cid', 0, 'intval');
        $one = SystemModel::field('appid, appsecret')->where('id', $cid)->find();
        $appid = $one['appid'];
        $appsecret = $one['appsecret'];
        $token = '';
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        $result = curl($url);
        if (!isset($result['errcode'])) {
            $token = $result['access_token'];
            Cache::set(config('cache.redis.prefix') . '_accesstoken', $token, 3600);
        }
        return $token;
    }

    /* 发送模板消息 */
    public function send()
    {
        if (!$this->request->auth) return show(config('status.auth'), 'Authorization Failed');
        $cid = input('cid', 0, 'intval');
        $first = input('first', '');
        $keyword1 = input('keyword1', '');
        $keyword2 = input('keyword2', '');
        $remark = input('remark', '');
        $url = input('url', '');

        $one = TemplateModel::where('cid', $cid)->find();
        if (!$one) {
            $result = TemplateModel::create([
                'cid' => $cid,
                'first' => $first,
                'keyword1' => $keyword1,
                'keyword2' => $keyword2,
                'remark' => $remark,
                'url' => $url
            ]);
        } else {
            $result = TemplateModel::update([
                'first' => $first,
                'keyword1' => $keyword1,
                'keyword2' => $keyword2,
                'remark' => $remark,
                'url' => $url
            ], ['cid' => $cid]);
        }

        $token = $this->getToken($cid);
        $requestUrl = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=' . $token;
        $result = curl($requestUrl);
        $openids = $result['data']['openid'];

        foreach ($openids as $v) {
            $data = [
                'token' => $token,
                'openid' => $v,
                'first' => $first,
                'keyword1' => $keyword1,
                'keyword2' => $keyword2,
                'remark' => $remark,
                'url' => $url
            ];
            // 延迟时间，文件路径，预备数据，php命令名称
            // later[延迟执行]、push[立即执行], 单位：秒
            Queue::later(5, 'app\admin\queue\Template', $data, 'sendTemplate');
        }
        return show(config('status.success'), '模板信息发送成功');
    }
}
